package cn.sky.demo.sso.client;

import cn.sky.demo.test.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

//@Component
public class SsoFilter implements Filter{

    @Autowired
    private RestTemplate restTemplate;
    
    private static final String SSO_SERVER_URL="https://sso.example.com";
    private static final String SSO_VALIDATION_URL= SSO_SERVER_URL + "/sso/validate";
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest= (HttpServletRequest) request;
        HttpServletResponse httpResponse= (HttpServletResponse) response;
        
        // 检查当前应用是否已有本地Session
        HttpSession currentSession= httpRequest.getSession(false);
        if (currentSession != null && currentSession.getAttribute("USER_INFO") != null) {
            // 已有本地Session，继续请求
            chain.doFilter(request, response);
            return;
        }
        
        // 获取SSO Session Cookie
        Cookie[] cookies = httpRequest.getCookies();
        String ssoSessionId=null;
        
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("SSO_SESSION_ID".equals(cookie.getName())) {
                    ssoSessionId = cookie.getValue();
                    break;
                }
            }
        }
        
        // 未找到SSO Cookie，重定向到SSO登录页
        if (ssoSessionId == null) {
            String redirectUrl= SSO_SERVER_URL + "/login?redirect=" +
                                URLEncoder.encode(httpRequest.getRequestURL().toString(), "UTF-8");
            httpResponse.sendRedirect(redirectUrl);
            return;
        }
        
        // 验证SSO Session有效性
        try {
            HttpHeaders headers=new HttpHeaders();
            headers.add("Cookie", "SSO_SESSION_ID=" + ssoSessionId);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            ResponseEntity<UserInfo> responseEntity = restTemplate.exchange(
                    SSO_VALIDATION_URL, HttpMethod.GET, entity, UserInfo.class);
            
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                // SSO Session有效，创建本地Session
                UserInfo userInfo= responseEntity.getBody();
                HttpSession session= httpRequest.getSession(true);
                session.setAttribute("USER_INFO", userInfo);
                
                chain.doFilter(request, response);
            } else {
                // SSO Session无效，重定向到登录页
                String redirectUrl= SSO_SERVER_URL + "/login?redirect=" +
                                    URLEncoder.encode(httpRequest.getRequestURL().toString(), "UTF-8");
                httpResponse.sendRedirect(redirectUrl);
            }
        } catch (Exception e) {
            // 验证过程出错，重定向到登录页
            String redirectUrl= SSO_SERVER_URL + "/login?redirect=" +
                                URLEncoder.encode(httpRequest.getRequestURL().toString(), "UTF-8");
            httpResponse.sendRedirect(redirectUrl);
        }
    }
}